package exercise;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @classname:DateUtil
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/9 21:44
 * @version: 0.1
 * @since:1.8
 */
public class DateUtil {

    private static final String PATTERN = "yyyy-MM-dd HH-mm-ss";
    //SimpleDateFormat是线程不安全，不能作为成员变量使用
    //Str --Date
    //交给ThreadLocal管理
    //默认执行initialValue
    private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL = new ThreadLocal(){
        //重写initialValue
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(PATTERN);
        }
    };

    public static synchronized Date strConvertToDate(String dateStr) {
        Objects.requireNonNull(dateStr);
        Date parse = null;
        try {
            parse = THREAD_LOCAL.get().parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }
    //Date转换str
    public static synchronized String DateConvertToStr(Date date) {
        Objects.requireNonNull(date);
        String format = THREAD_LOCAL.get().format(date);
        return format;
     }
}
